package com.atguigu.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class TestYield2 {

    private Integer num = 1;

    public static void main(String[] args) {

        TestYieldThread2 testYieldThread2 = new TestYieldThread2();
        ReentrantLock lock = testYieldThread2.getLock();

        new Thread(() -> {
            try {
                for (int i = 1; i <= 50; i++) {
                    testYieldThread2.get();
                    if (testYieldThread2.getNum() % 2 == 0) {
                        while (lock.isLocked()) {
                            lock.unlock();
                        }
                        Thread.sleep(1000);
                        Thread.yield();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if (lock.isLocked()) {
                    lock.unlock();
                }
            }
        }, "AAAA").start();

        new Thread(() -> {

            try {
                for (int i = 1; i <= 50; i++) {
                    testYieldThread2.get();
                    if (testYieldThread2.getNum() % 2 == 0) {
                        while (lock.isLocked()) {
                            lock.unlock();
                        }
                        Thread.sleep(1000);
                        Thread.yield();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if (lock.isLocked()) {
                    lock.unlock();
                }
            }
        }, "BBBB").start();

    }


}

class TestYieldThread2 {

    private Integer num = 0;

    private static ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void get() throws InterruptedException {
        lock.lock();
        condition.signalAll();
        num++;
        System.out.println(Thread.currentThread().getName() + " : " + num);
    }


    public Integer getNum() {
        return num;
    }

    public ReentrantLock getLock() {
        return lock;
    }
}
